package com.kevin.spring.service;

import com.kevin.annotation.RemoteService;
import com.kevin.protocol.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.lang.reflect.Method;

/**
 * 在afterPropertiesSet之后启动netty服务，postProcessAfterInitialization在bean实例化之后将方法和bean信息
 * 缓存到集合中
 */
@Slf4j
public class SpringRpcProviderBean implements InitializingBean, BeanPostProcessor {

    private String serviceIp;

    private int servicePort;


    public SpringRpcProviderBean(String serviceIp, int servicePort) {
        this.serviceIp = serviceIp;
        this.servicePort = servicePort;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("begin deploy Netty Server to host {},on port {}",this.serviceIp,this.servicePort);
        new Thread(()->{
            new NettyServer(this.serviceIp,this.servicePort).startServer();
        }).start();
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //指针对标注了RemoteService注解的类进行处理
        if(bean.getClass().isAnnotationPresent(RemoteService.class)){
            for (Method method : bean.getClass().getDeclaredMethods()) {
                String serviceName = bean.getClass().getInterfaces()[0].getName();
                String invokeKey = serviceName+"."+method.getName();
                HandlerMapping.handlerMethodMap.put(invokeKey,new BeanMethod(bean,method));
                log.info("注册服务：{}",invokeKey);
            }
        }
        return null;
    }
}
